﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;

namespace GUI
{
    public partial class frmManHinhChinh : Form
    {
        public frmManHinhChinh()
        {
            InitializeComponent();
        }
        
        //--------------------------
        //biến toàn cục tính toán công suất
        float TongW_TBSuDung = 0; //tổng w mà các tb sử dụng tại 1 thời điểm, ko xuyên suốt
        float TongCS_TB = 0; //tổng công suất tất cả thiết bị sử dụng
        float TongCS_Pin = 0; //tổng công suất tấm pin, thường = 1,3 đến 1,5 tổng cs thiết bị, ta chọn gấp 1,3
        float TongWp_Pin = 0;
        float DungLuongAcquy = 0;
        //biến toàn cục cho form
        bool isLoad = false;
        ///bool duphongcupdien = false;

        //chung
        float TongW_TBSuDung_Chung = 0;
        float TongCS_TB_Chung = 0;
        //--------------------------

        private void btnKeTiep_Click(object sender, EventArgs e)
        {
            tabControl2.SelectedTab = tpLuaChonKH;
            lbTongCongSuat_LuaChon.Text = lbTongCongSuat.Text;
        }

        private void btnQuayLai_Click(object sender, EventArgs e)
        {
            tabControl2.SelectedTab = tpTongCongSuat;
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnTongCongSuat_Click(object sender, EventArgs e)
        {
            int n = dgvNhapThietBi.RowCount;
            float s = 0;
            if (n > 1)
            {
                try 
                {
                    for (int i = 0; i < n - 1; i++)
                    {
                        s += float.Parse(dgvNhapThietBi.Rows[i].Cells[6].Value.ToString());
                        TongW_TBSuDung_Chung += (float.Parse(dgvNhapThietBi.Rows[i].Cells[2].Value.ToString()) + float.Parse(dgvNhapThietBi.Rows[i].Cells[3].Value.ToString()));
                    }
                    lbTongCongSuat.Text = s.ToString() + " W";
                    //Hiển thị sau khi tính toán tổng công suất
                    btnKeTiep.Enabled = true;
                    TongCS_TB_Chung = s;
                    //TongCS_Pin = (float)(TongCS_TB_Chung * 1.3);
                }
                catch { MessageBox.Show("Vui lòng điền đầy đủ thông tin..."); };
            }
        }

        private void ts_btnThietBi_Click(object sender, EventArgs e)
        {
            pnLuuTruCapNhat.Controls.Clear();
            ucThietBiDienTu u = new ucThietBiDienTu();
            if (flag) u.XuLy();
            pnLuuTruCapNhat.Controls.Add(u);
            u.Dock = DockStyle.Fill;

        }

        private void ts_btnThietBiThongDung_Click(object sender, EventArgs e)
        {
            pnLuuTruCapNhat.Controls.Clear();
            ucThietBiThongDung u = new ucThietBiThongDung();
            pnLuuTruCapNhat.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        private void ts_btnKhuVuc_Click(object sender, EventArgs e)
        {
            pnLuuTruCapNhat.Controls.Clear();
            ucKhuVuc u = new ucKhuVuc();
            pnLuuTruCapNhat.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        private void ts_btnDoiMatKhau_Click(object sender, EventArgs e)
        {
            pnHeThong.Controls.Clear();
            ucDoiMatKhau u = new ucDoiMatKhau();
            u.doiMatKhau += new EventHandler(u_dangNhap);
            pnHeThong.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        private void ts_btnDangNhap_Click(object sender, EventArgs e)
        {
            pnHeThong.Controls.Clear();
            ucDangNhap u = new ucDangNhap();
            u.dangNhap += new EventHandler(u_dangNhap);
            pnHeThong.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        bool flag = false;
        void u_dangNhap(object sender, EventArgs e)
        {
            ts_btnDoiMatKhau.Enabled = true;
            ts_btnSaoLuu.Enabled = true;
            ts_btnDangXuat.Enabled = true;
            ts_btnPhucHoi.Enabled = true;
            ts_btnDangNhap.Enabled = false;
            flag = true;
        }

        private void ts_btnPhucHoi_Click(object sender, EventArgs e)
        {
            pnHeThong.Controls.Clear();
            ucPhucHoi u = new ucPhucHoi();
            pnHeThong.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        private void ts_btnSaoLuu_Click(object sender, EventArgs e)
        {
            pnHeThong.Controls.Clear();
            ucSaoLuu u = new ucSaoLuu();
            pnHeThong.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        private void ts_btnExportBangBaoGia_Click(object sender, EventArgs e)
        {
            pnHeThong.Controls.Clear();
            ucExport u = new ucExport();
            pnHeThong.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        private void ts_btnExportKQTuVan_Click(object sender, EventArgs e)
        {
            pnHeThong.Controls.Clear();
            ucExport u = new ucExport();
            pnHeThong.Controls.Add(u);
            u.Dock = DockStyle.Fill;
        }

        void InsertFirstRow(DataTable dt)
        {
            DataRow dr = dt.NewRow();
            dr[0] = 0;
            dr[1] = "Vui lòng chọn...";
            dt.Rows.InsertAt(dr ,0);
        }

        private void frmManHinhChinh_Load(object sender, EventArgs e)
        {
            try
            {
                KhuVucBus.DanhSachKhuVuc();
            }
            catch (Exception ex)
            {
                frmConfig frm = new frmConfig();
                frm.ShowDialog();
                frmManHinhChinh_Load(sender, e);
            }
            cbbCachSuDung.SelectedIndex = 0;
            DataTable dt = ThietBiThongDungBUS.DanhSachTBTD();
            InsertFirstRow(dt);
            cbbDanhSachTBTD.DataSource = dt;
            cbbDanhSachTBTD.DisplayMember = "TenThietBiThongDung";
            cbbDanhSachTBTD.ValueMember = "MaThietBiThongDung";

            DataTable tracuu = ThietBiDienBUS.DanhSach("select * from LOAITHIETBIDIEN");
            InsertFirstRow(tracuu);
            cbbLoaiThietBi_TraCuu.DataSource = tracuu;
            cbbLoaiThietBi_TraCuu.DisplayMember = "TenLoaiThietBi";
            cbbLoaiThietBi_TraCuu.ValueMember = "MaLoaiThietBi";

            DataTable dt2 = ThietBiDienBUS.DanhSach("usp_DanhSachPin");
            //InsertFirstRow(dt2);
            cbbLoaiPin.DataSource = dt2;
            cbbLoaiPin.DisplayMember = "TenLoaiThietBi";
            cbbLoaiPin.ValueMember = "MaLoaiThietBi";

            DataTable dt3 = ThietBiDienBUS.DanhSach("usp_DanhSachAcquy");
            //InsertFirstRow(dt3);
            cbbLoaiAcquy.DataSource = dt3;
            cbbLoaiAcquy.DisplayMember = "TenLoaiThietBi";
            cbbLoaiAcquy.ValueMember = "MaLoaiThietBi";
            cbbLoaiAcquy.SelectedIndex = 2;

            DataTable dt4 = ThietBiDienBUS.DanhSach("usp_DanhSachBoKichDien");
            //InsertFirstRow(dt4);
            cbbBoKichDien.DataSource = dt4;
            cbbBoKichDien.DisplayMember = "TenLoaiThietBi";
            cbbBoKichDien.ValueMember = "MaLoaiThietBi";

            DataTable dt5 = ThietBiDienBUS.DanhSach("usp_DanhSachBoDieuKhienSac");
           // InsertFirstRow(dt5);
            cbbBoDKSac.DataSource = dt5;
            cbbBoDKSac.DisplayMember = "TenLoaiThietBi";
            cbbBoDKSac.ValueMember = "MaLoaiThietBi";

            DataTable dt6 = ThietBiDienBUS.DanhSach("usp_DanhSachKhuVuc");
            //InsertFirstRow(dt6);
            cbbKhuVuc.DataSource = dt6;
            cbbKhuVuc.DisplayMember = "TenKhuVuc";
            cbbKhuVuc.ValueMember = "SoGioNang";

            //load txtSoGioNang
            txtSoGioNang.Text = cbbKhuVuc.SelectedValue.ToString();
            //isLoad = true;
        }

        private void cbbDanhSachTBTD_SelectedIndexChanged(object sender, EventArgs e)
        {
            int ma = cbbDanhSachTBTD.SelectedIndex;
            if (ma > 0)
            {
                DataTable dt = ThietBiThongDungBUS.LayDSTBTDTheoMa(ma);
                txtTenThietBi.Text = dt.Rows[0][1].ToString();
                txtCongSuatTieuThu.Text = dt.Rows[0][2].ToString();
                txtCongSuatHaoHut.Text = dt.Rows[0][3].ToString();
                txtHeSoDeBa.Value = int.Parse(dt.Rows[0][4].ToString());
                txtThoiGianSDTrongNgay.Focus();
                txtThoiGianSDTrongNgay.SelectAll();
            }
            else
            {
                txtTenThietBi.Text = "";
                txtCongSuatTieuThu.Text = "";
                txtCongSuatHaoHut.Text = "";
                txtHeSoDeBa.Value = 1;
                txtTenThietBi.Focus();
                txtTenThietBi.SelectAll();
            }
        }

        int i = 0;
        private bool KTraNhap(object sender, EventArgs e)
        {
            if (txtTenThietBi.Text == "") { MessageBox.Show("Nhập tên thiết bị..."); txtTenThietBi.Focus(); return false; }
            if (txtCongSuatTieuThu.Text == "") { MessageBox.Show("Nhập công suất tiêu thụ..."); txtCongSuatTieuThu.Focus(); return false; }
            if (txtCongSuatHaoHut.Text == "") { MessageBox.Show("Nhập công suất hao hụt..."); txtCongSuatHaoHut.Focus(); return false; }
            if (txtThoiGianSDTrongNgay.Text == "") { MessageBox.Show("Nhập thời gian sử dụng..."); txtThoiGianSDTrongNgay.Focus(); return false; }

            int SoLuong = int.Parse(txtSoLuong.Value.ToString());
            int HeSoDeBa = int.Parse(txtHeSoDeBa.Value.ToString());
            double CongSuatTieuThu = double.Parse(txtCongSuatTieuThu.Text);
            double CongSuatTieuHao = double.Parse(txtCongSuatHaoHut.Text);
            double ThoiGianSuDung = double.Parse(txtThoiGianSDTrongNgay.Text);
            double CongSuatTong = (CongSuatTieuThu + CongSuatTieuHao) * SoLuong * HeSoDeBa * ThoiGianSuDung;

            DataGridViewRow dr = new DataGridViewRow();
            dgvNhapThietBi.Rows.Add(dr);
            dgvNhapThietBi.Rows[i].Cells[0].Value = txtTenThietBi.Text;
            dgvNhapThietBi.Rows[i].Cells[1].Value = SoLuong;
            dgvNhapThietBi.Rows[i].Cells[2].Value = CongSuatTieuThu;
            dgvNhapThietBi.Rows[i].Cells[3].Value = CongSuatTieuHao;
            dgvNhapThietBi.Rows[i].Cells[4].Value = HeSoDeBa;
            dgvNhapThietBi.Rows[i].Cells[5].Value = ThoiGianSuDung;
            dgvNhapThietBi.Rows[i].Cells[6].Value = CongSuatTong;
            i++;
            btnTongCongSuat.PerformClick();
            btnKeTiep.Enabled = true;
            return true;
        }

        bool co = false;
        private void btnNhap_Click(object sender, EventArgs e)
        {
            co = KTraNhap(sender, e);
        }

        private void txtCongSuatTieuThu_KeyPress(object sender, KeyPressEventArgs e)
        {
            //Không đc nhập chữ và cho phép sử dụng dấu '.', backspace
            if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar)) && e.KeyChar != '.')
                e.Handled = true;
        }

        private void txtNgayCupDien_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar)) && e.KeyChar != '.')
                e.Handled = true;
        }

        private void txtCongSuatHaoHut_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar)) && e.KeyChar != '.')
                e.Handled = true;
        }

        private void txtThoiGianSDTrongNgay_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar)) && e.KeyChar != '.')
                e.Handled = true;
        }

        private void btnLamMoi_Click(object sender, EventArgs e)
        {
            dgvNhapThietBi.Rows.Clear();
            i = 0; iRow = -1;
            cbbDanhSachTBTD.SelectedIndex = 0;
            btnKeTiep.Enabled = false;
            lbTongCongSuat.Text = "W";
            txtSoLuong.Value = txtHeSoDeBa.Value = 1;
            txtTenThietBi.Text = txtCongSuatTieuThu.Text = txtCongSuatHaoHut.Text = txtThoiGianSDTrongNgay.Text = null;
        }

        double CongSuatTungThietBi(int n)
        {
            return (double.Parse(dgvNhapThietBi.Rows[n].Cells[2].Value.ToString())
                   + double.Parse(dgvNhapThietBi.Rows[n].Cells[3].Value.ToString()))
                   * int.Parse(dgvNhapThietBi.Rows[n].Cells[4].Value.ToString())
                   * double.Parse(dgvNhapThietBi.Rows[n].Cells[5].Value.ToString())
                   * double.Parse(dgvNhapThietBi.Rows[n].Cells[1].Value.ToString());
        }

        private void dgvNhapThietBi_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            int n = dgvNhapThietBi.CurrentRow.Index;
            switch (e.ColumnIndex)
            {
                case 1:
                    //Ktra nhập liệu
                    if (dgvNhapThietBi.CurrentCell.Value == null) 
                        dgvNhapThietBi.CurrentCell.Value = dTemp;
                    else
                        //Ktra KDL nhập
                        try
                        {
                            dgvNhapThietBi.Rows[n].Cells[6].Value = CongSuatTungThietBi(n);
                            btnTongCongSuat.PerformClick();
                        }
                        catch {};
                    break;
                case 2:
                    if (dgvNhapThietBi.CurrentCell.Value == null)
                        dgvNhapThietBi.CurrentCell.Value = dTemp;
                    else
                        try
                        {
                            dgvNhapThietBi.Rows[n].Cells[6].Value = CongSuatTungThietBi(n);
                            btnTongCongSuat.PerformClick();
                        }
                        catch {};
                    
                    break;
                case 3:
                    if (dgvNhapThietBi.CurrentCell.Value == null)
                        dgvNhapThietBi.CurrentCell.Value = dTemp;
                    else
                        try
                        {
                            dgvNhapThietBi.Rows[n].Cells[6].Value = CongSuatTungThietBi(n);
                            btnTongCongSuat.PerformClick();
                        }
                        catch {};
                    break;
                case 4:
                    if (dgvNhapThietBi.CurrentCell.Value == null)
                        dgvNhapThietBi.CurrentCell.Value = dTemp;
                    else
                        try
                        {
                            dgvNhapThietBi.Rows[n].Cells[6].Value = CongSuatTungThietBi(n);
                            btnTongCongSuat.PerformClick();
                        }
                        catch {};
                    break;
                case 5:
                    if (dgvNhapThietBi.CurrentCell.Value == null)
                        dgvNhapThietBi.CurrentCell.Value = dTemp;
                    else
                        try
                        {
                            dgvNhapThietBi.Rows[n].Cells[6].Value = CongSuatTungThietBi(n);
                            btnTongCongSuat.PerformClick();
                            if (iRow > -1)
                            {
                                i = iRow + 1;
                                iRow = -1;
                                btnTongCongSuat.PerformClick();
                                btnKeTiep.Enabled = true;
                            }
                        }
                        catch {};
                    break;
            }
        }

        void txt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                MessageBox.Show("enter");
        }

        int iRow = -1;
        private void dgvNhapThietBi_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            iRow = e.Row.Index - 1;
            lbTongCongSuat.Text = "W";
            btnKeTiep.Enabled = false;
        }

        private void dgvNhapThietBi_KeyDown(object sender, KeyEventArgs e)
        {
            int n = dgvNhapThietBi.CurrentRow.Index;
            if (n < dgvNhapThietBi.Rows.Count - 1)
                if (e.KeyCode == Keys.Delete)
                    if (MessageBox.Show("Bạn có thật sự muốn xóa dòng này?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        lbTongCongSuat.Text = "W";
                        btnKeTiep.Enabled = false;
                        dgvNhapThietBi.Rows.Remove(dgvNhapThietBi.Rows[n]);
                        i = i - 1;
                        btnTongCongSuat.PerformClick();
                    }
        }

        private void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txt = sender as TextBox;
            if (txt.Name == "Col")
                try
                {
                    //Không đc nhập chữ và cho phép sử dụng dấu '.', backspace
                    if (!Char.IsDigit(e.KeyChar) && (!Char.IsControl(e.KeyChar)) && e.KeyChar != '.')
                          e.Handled = true;
                }
                catch { };
        }

        private void dgvNhapThietBi_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            TextBox txt = e.Control as TextBox;
            txt.Name = "";
            if (dgvNhapThietBi.CurrentCellAddress.X != dgvNhapThietBi.Columns[0].DisplayIndex)
            {
                txt.Name = "Col";
                if (txt != null)
                {
                    txt.KeyPress += new KeyPressEventHandler(txt_KeyPress);
                }
            }
        }

        string dTemp;
        private void dgvNhapThietBi_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            var a = dgvNhapThietBi.CurrentCell.Value;
            if (e.ColumnIndex > 0)
                if (a != null)
                    dTemp = a.ToString();   
        }

        private void ts_btnDangXuat_Click(object sender, EventArgs e)
        {
            ts_btnDoiMatKhau.Enabled = false;
            ts_btnSaoLuu.Enabled = false;
            ts_btnDangXuat.Enabled = false;
            ts_btnPhucHoi.Enabled = false;
            ts_btnDangNhap.Enabled = true;
            flag = false;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 2)
                ts_btnThietBi.PerformClick();
            if (tabControl1.SelectedIndex == 3)
                ts_btnDangNhap.PerformClick();
        }

        private void txtThoiGianSDTrongNgay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnNhap.PerformClick();
                if (co)
                {
                    txtTenThietBi.Focus();
                    txtTenThietBi.SelectAll();
                }
            }
        }

        private void txtTenThietBi_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtSoLuong.Focus();
                txtSoLuong.Select(1, 5);
            }
        }

        private void txtSoLuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtHeSoDeBa.Focus();
                txtHeSoDeBa.Select(1, 5);
            }
        }

        private void txtHeSoDeBa_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtCongSuatTieuThu.Focus();
                txtCongSuatTieuThu.SelectAll();
            }
        }

        private void txtCongSuatTieuThu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtCongSuatHaoHut.Focus();
                txtCongSuatHaoHut.SelectAll();
            }
        }

        private void txtCongSuatHaoHut_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtThoiGianSDTrongNgay.Focus();
                txtThoiGianSDTrongNgay.SelectAll();
            }
        }

        private void btnNhap_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                txtTenThietBi.Focus();
                txtTenThietBi.SelectAll();
            }
        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (btnKeTiep.Enabled == false && tabControl2 .SelectedTab != tpTongCongSuat)
                {
                    MessageBox.Show("Nhập thiết bị điện trước khi tư vấn");
                    tabControl2.SelectedTab = tpTongCongSuat;
                }
                else
                {
                    lbTongCongSuat_LuaChon.Text = lbTongCongSuat.Text;

                    CachDung();

                    //pin - chọn pin thích hợp, là pin có cs < tổng cs pin
                    TinhToan_Pin(int.Parse(cbbLoaiPin.SelectedValue.ToString()));


                    //acquy
                    TinhToan_Acquy(int.Parse(cbbLoaiAcquy.SelectedValue.ToString()));

                    //sạc     
                    TinhToan_BoDieuKhienSac(cbbBoDKSac.SelectedIndex);

                    //kích điện
                    TinhToan_BoKichDien(int.Parse(cbbBoKichDien.SelectedValue.ToString()));

                    TongTien();
                    isLoad = true;
                }

            }
            catch { };
        }



        //hàm chuyển đổi cách dùng
        public void CachDung()
        {
            int ngaycupdien = 1;
            if (cbbCachSuDung.SelectedIndex == 1)
            {
                //lấy số ngày cúp điện
                ngaycupdien = int.Parse(txtNgayCupDien.Text);
                //tính lại TongCS_TB
                TongCS_TB = TongCS_TB_Chung / ngaycupdien;   
            }
            else
            {
                TongCS_TB = TongCS_TB_Chung;
                
            }
            TongCS_Pin = (float)(TongCS_TB * 1.3);
            TongWp_Pin = TongCS_Pin / (float.Parse(txtSoGioNang.Text));
            TongW_TBSuDung = TongW_TBSuDung_Chung;
        }

        //---------------------------------------------------------------------------------------------------------
        
        public DataTable Retrieve_ThietBi(int MaThietBi)
        {
            return ThietBiDienBUS.Retrieve_ThietBi(MaThietBi);
        }

        public void TinhToan_BoKichDien(int ma)
        {
            //ChiaCachSuDung();
            if (TongW_TBSuDung * 125 / 100 > 500)
            {
                //lấy ds bộ kích điện loại theo cbb Loai và có W> tổng cs thiết bị tại 1 thời điểm *125%
                float W = TongW_TBSuDung * 125 / 100;
                DataTable dt_BKD = ThietBiDienBUS.Retrieve_BoKichDien(ma, W);
                cbbKQKichDien.DataSource = dt_BKD;
                cbbKQKichDien.DisplayMember = "CongSuat";
                cbbKQKichDien.ValueMember = "MaThietBi";

                //lấy thông tin show dongia và thanhtien

                if (dt_BKD.Rows.Count != 0)
                {
                    DataTable dt = Retrieve_ThietBi(int.Parse(cbbKQKichDien.SelectedValue.ToString()));
                    if (dt.Rows.Count != 0)
                    {
                        txtSLBKD.Text = "1";
                        txtDGBKD.Text = (double.Parse(dt.Rows[0]["DonGia"].ToString()) / 1000).ToString();
                        txtThanhTienBKD.Text = txtDGBKD.Text;
                    }
                    lblThongBao_BKD.Text = "";
                }
                else
                    lblThongBao_BKD.Text = "Không có bộ kích điện phù hợp";
            }
            else
            {
                txtSLBKD.Text = "0";
                txtThanhTienBKD.Text = "0";
                txtDGBKD.Text = "0";
                lblThongBao_BKD.Text = "Không cần sử dụng bộ kích điện";
            }
            TongTien();
        }

        public void TinhToan_BoDieuKhienSac(int index)
        {
            //ChiaCachSuDung();
            cbbKQSac.DataSource = ThietBiDienBUS.Retrieve_BoSac(int.Parse(cbbBoDKSac.SelectedValue.ToString()));
            cbbKQSac.ValueMember = "MaThietBi";
            cbbKQSac.DisplayMember = "TenThietBi";
            int heso = 1;
            switch (index)
            {
                case 0:
                    heso = 1;
                    break;
                case 1:
                    heso = 2;
                    break;
                case 2:
                    heso = 4;
                    break;
            }
            
            //lấy loại pin để biết đc Isc
            DataTable dt = Retrieve_ThietBi(int.Parse(cbbKQPin.SelectedValue.ToString()));
            if (dt.Rows.Count != 0)
            {
                float Isc = float.Parse(dt.Rows[0]["IscA"].ToString());

                float machsac = (float)((int.Parse(txtSLPin.Text) * Isc * 1.3) / heso);

                //chọn loại mạch sạc có loại = loại của cbbBoSac, có A > machsac (theo pin)
                

                DataTable dt_Sac = Retrieve_ThietBi(int.Parse(cbbKQSac.SelectedValue.ToString()));
                if (dt_Sac.Rows.Count != 0)
                {
                    int soluong = (int)(machsac / int.Parse(dt_Sac.Rows[0]["ImpA"].ToString()) +0.999);
                    txtSLSac.Text = soluong.ToString();
                    double dongia = double.Parse(dt_Sac.Rows[0]["DonGia"].ToString()) / 1000;
                    txtDGSac.Text = dongia.ToString();
                    txtThanhTienSac.Text = (int.Parse(txtSLSac.Text) * dongia).ToString();
                }
            }
            TongTien();
        }

        public void TinhToan_Acquy(int ma)
        {
            cbbKQAcquy.DataSource = ThietBiDienBUS.Retrive_Acquy(ma);
            cbbKQAcquy.DisplayMember = "TenThietBi";
            cbbKQAcquy.ValueMember = "MaThietBi";

            int MaThietBi = int.Parse(cbbKQAcquy.SelectedValue.ToString());
            DataTable dt = ThietBiDienBUS.Retrieve_ThietBi(MaThietBi);
            if (dt.Rows.Count != 0)
            {
                float Wh = float.Parse(dt.Rows[0]["ImpA"].ToString());
                float DienTheAcquy = float.Parse(dt.Rows[0]["VmpV"].ToString());

                //số lượng
                DungLuongAcquy = (float)(TongCS_TB / (0.85 * 0.6 * DienTheAcquy));
                int slAcquy = (int)(DungLuongAcquy / Wh + 0.999);
                txtSLAcquy.Text = slAcquy.ToString();
                //đơn giá
                double dongia = double.Parse(dt.Rows[0]["DonGia"].ToString()) / 1000;
                txtDGAcquy.Text = dongia.ToString();
                //thành tiền
                txtThanhTienAcquy.Text = (dongia * slAcquy).ToString();
            }
            TongTien();
        }
        
        public void TinhToan_Pin(int ma)
        {
            cbbKQPin.DataSource = ThietBiDienBUS.Retrieve_Pin(TongWp_Pin, ma);
            cbbKQPin.ValueMember = "MaThietBi";
            cbbKQPin.DisplayMember = "CongSuat";

            //------------------------
            //lấy pin đã đc chọn
            int MaThietBi = int.Parse(cbbKQPin.SelectedValue.ToString());
            DataTable dt = Retrieve_ThietBi(MaThietBi);

            //------------------------
            if (dt.Rows.Count != 0)
            {
                float congsuat = float.Parse(dt.Rows[0]["CongSuat"].ToString());

                //số lượng
                if ((TongWp_Pin / congsuat) < 1) { txtSLPin.Text = "1"; }
                else txtSLPin.Text = ((int)(TongWp_Pin / congsuat + 0.9)).ToString();

                //đơn giá
                double dongia = double.Parse(dt.Rows[0]["DonGia"].ToString()) / 1000;
                txtDGPin.Text = dongia.ToString();

                //thành tiền
                float thanhtien_pin = int.Parse(txtSLPin.Text) * float.Parse(txtDGPin.Text);
                txtThanhTienPin.Text = thanhtien_pin.ToString();
            }
            TongTien();
        }

        

        private void cbbKQPin_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
            {
                int MaThietBi = int.Parse(cbbKQPin.SelectedValue.ToString());
                DataTable dt = Retrieve_ThietBi(MaThietBi);

                //------------------------
                if (dt.Rows.Count != 0)
                {
                    float congsuat = float.Parse(dt.Rows[0]["CongSuat"].ToString());

                    //số lượng
                    if ((TongWp_Pin / congsuat) < 1) { txtSLPin.Text = "1"; }
                    else txtSLPin.Text = ((int)(TongWp_Pin / congsuat + 0.9)).ToString();

                    //đơn giá
                    double dongia = double.Parse(dt.Rows[0]["DonGia"].ToString()) / 1000;
                    txtDGPin.Text = dongia.ToString();

                    //thành tiền
                    double thanhtien_pin = int.Parse(txtSLPin.Text) * double.Parse(txtDGPin.Text);
                    txtThanhTienPin.Text = thanhtien_pin.ToString();
                }
                cbbKQSac_SelectedIndexChanged(sender, e);
            }
            TongTien();
        }

        private void cbbKQAcquy_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
            {
                int MaThietBi = int.Parse(cbbKQAcquy.SelectedValue.ToString());
                DataTable dt = Retrieve_ThietBi(MaThietBi);
                if (dt.Rows.Count != 0)
                {
                    float Wh = float.Parse(dt.Rows[0]["ImpA"].ToString());
                    float DienTheAcquy = float.Parse(dt.Rows[0]["VmpV"].ToString());

                    //số lượng
                    DungLuongAcquy = (float)(TongCS_TB / (0.85 * 0.6 * DienTheAcquy));
                    int slAcquy = (int)(DungLuongAcquy / Wh + 0.999);
                    txtSLAcquy.Text = slAcquy.ToString();
                    //đơn giá
                    double dongia = double.Parse(dt.Rows[0]["DonGia"].ToString()) / 1000;
                    txtDGAcquy.Text = dongia.ToString();
                    //thành tiền
                    txtThanhTienAcquy.Text = (dongia * slAcquy).ToString();
                }          
            }
            TongTien();
        }

        private void cbbLoaiPin_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(isLoad)
                TinhToan_Pin(int.Parse(cbbLoaiPin.SelectedValue.ToString()));
        }

        private void cbbLoaiAcquy_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
                TinhToan_Acquy(int.Parse(cbbLoaiAcquy.SelectedValue.ToString()));
        }

        private void cbbKhuVuc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
            {
                txtSoGioNang.Text = cbbKhuVuc.SelectedValue.ToString();
                ChuyenDoi(sender, e);
            }
        }

        private void cbbCachSuDung_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
            {
                switch (cbbCachSuDung.SelectedIndex)
                {
                    case 0:
                        txtNgayCupDien.ReadOnly = true;
                        txtNgayCupDien.Text = "";
                        ChuyenDoi(sender, e);
                        break;
                    case 1:
                        txtNgayCupDien.ReadOnly = false;
                        txtNgayCupDien.Text = "1";
                        ChuyenDoi(sender, e);
                        break;
                }
            }
        }

        private void cbbKQKichDien_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
            {
                if (TongW_TBSuDung * 125 / 100 > 500)
                {
                    //lấy ds bộ kích điện loại theo cbb Loai và có W> tổng cs thiết bị tại 1 thời điểm *125%
                    float W = TongW_TBSuDung * 125 / 100;
                    DataTable dt_BKD = ThietBiDienBUS.Retrieve_BoKichDien(int.Parse(cbbBoKichDien.SelectedValue.ToString()), W);
                    if (dt_BKD.Rows.Count != 0)
                    {
                        DataTable dt = Retrieve_ThietBi(int.Parse(cbbKQKichDien.SelectedValue.ToString()));
                        if (dt.Rows.Count != 0)
                        {
                            txtSLBKD.Text = "1";
                            txtDGBKD.Text = (double.Parse(dt.Rows[0]["DonGia"].ToString()) / 1000).ToString();
                            txtThanhTienBKD.Text = txtDGBKD.Text;
                        }
                        else
                            lblThongBao_BKD.Text = "Không có bộ kích điện phù hợp";
                    }
                }
                else
                    lblThongBao_BKD.Text = "Không cần bộ kích điện";
            }
            TongTien();
        }

        private void cbbKQSac_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
            {
                int heso = 1;
                switch (cbbBoDKSac.SelectedIndex)
                {
                    case 0:
                        heso = 1;
                        break;
                    case 1:
                        heso = 2;
                        break;
                    case 2:
                        heso = 4;
                        break;
                }

                //lấy loại pin để biết đc Isc
                DataTable dt = Retrieve_ThietBi(int.Parse(cbbKQPin.SelectedValue.ToString()));
                if (dt.Rows.Count != 0)
                {
                    float Isc = float.Parse(dt.Rows[0]["IscA"].ToString());

                    float machsac = (float)((int.Parse(txtSLPin.Text) * Isc * 1.3) / heso);

                    //chọn loại mạch sạc có loại = loại của cbbBoSac, có A > machsac (theo pin)


                    DataTable dt_Sac = Retrieve_ThietBi(int.Parse(cbbKQSac.SelectedValue.ToString()));
                    if (dt_Sac.Rows.Count != 0)
                    {
                        int soluong = (int)(machsac / int.Parse(dt_Sac.Rows[0]["ImpA"].ToString()) + 0.999);
                        txtSLSac.Text = soluong.ToString();
                        double dongia = double.Parse(dt_Sac.Rows[0]["DonGia"].ToString()) / 1000;
                        txtDGSac.Text = dongia.ToString();
                        txtThanhTienSac.Text = (int.Parse(txtSLSac.Text) * dongia).ToString();
                    }
                }
            }
            TongTien();
        }

        private void cbbBoDKSac_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad)
                TinhToan_BoDieuKhienSac(int.Parse(cbbBoDKSac.SelectedValue.ToString()));
        }

        private void txtNgayCupDien_TextChanged(object sender, EventArgs e)
        {
            if (cbbCachSuDung.SelectedIndex == 1)
            {
                if (txtNgayCupDien.Text != "")
                {
                    if (txtNgayCupDien.Text != "0")
                    {
                        int ngaycupdien = int.Parse(txtNgayCupDien.Text);
                        ChuyenDoi(sender, e);
                    }
                    else
                    {
                        txtNgayCupDien.Text = "1";
                        ChuyenDoi(sender, e);
                    }
                }
                else
                {
                    txtNgayCupDien.Text = "1";
                    ChuyenDoi(sender, e);
                }
            }
        }

        public void ChuyenDoi(object sender, EventArgs e)
        {
            CachDung();
            cbbKQPin_SelectedIndexChanged(sender, e);
            cbbKQAcquy_SelectedIndexChanged(sender, e);
            cbbKQSac_SelectedIndexChanged(sender, e);
            cbbKQKichDien_SelectedIndexChanged(sender, e);
            TongTien();
        }

        public void TongTien()
        {
            double tongtien, pin, acquy, sac, bkd;
            tongtien = pin = acquy = sac = bkd = 0;
            
            if(txtThanhTienPin .Text !="")
                pin = double.Parse(txtThanhTienPin.Text);
            if (txtThanhTienAcquy.Text != "")
                acquy = double.Parse(txtThanhTienAcquy.Text);
            if (txtThanhTienSac.Text != "")
                sac = double.Parse(txtThanhTienSac.Text);
            if (txtThanhTienBKD.Text != "")
                bkd = double.Parse(txtThanhTienBKD.Text);
            tongtien = pin + acquy + sac + bkd;
            txtTongTien.Text = tongtien.ToString() + ".000"; 
        }

        private void btnLamMoi_LuaChon_Click(object sender, EventArgs e)
        {
            tabControl2.SelectedTab = tpTongCongSuat;
            btnLamMoi.PerformClick();
        }

        private void btnThoat_TraCuu_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnLamMoi_TraCuu_Click(object sender, EventArgs e)
        {
            txtChieuDai_TraCuu.Text = string.Empty;
            txtChieuDay_TraCuu.Text = string.Empty;
            txtChieuRong_TraCuu.Text = string.Empty;
            txtCongSuat_TraCuu.Text = string.Empty;
            txtDonGia_TraCuu.Text = string.Empty;
            txtMaThietBi_TraCuu.Text = string.Empty;
            txtTenThietBi_TraCuu.Text = string.Empty;
            txtImp_TraCuu.Text = string.Empty;
            txtVmp_TraCuu.Text = string.Empty;
            txtIsc_TraCuu.Text = string.Empty;
            txtVoc_TraCuu.Text = string.Empty;
        }

        private void btnTraCuu_Click(object sender, EventArgs e)
        {
            ThietBiDienDTO _ThietBiDien = new ThietBiDienDTO();
            int _MaThietBi = 0;
            if (txtTenThietBi_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.TenThietBi = txtTenThietBi_TraCuu.Text.ToString();
            }
            else
            {
                _ThietBiDien.TenThietBi = string.Empty;
            }
            if (txtMaThietBi_TraCuu.Text != string.Empty)
            {
                _MaThietBi = int.Parse(txtMaThietBi_TraCuu.Text.ToString());
            }
            if (txtCongSuat_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.CongSuat = double.Parse(txtCongSuat_TraCuu.Text.ToString());
            }
            if (cbbLoaiThietBi_TraCuu.SelectedValue.ToString() != "0")
            {
                _ThietBiDien.MaLoaiThietBi = int.Parse(cbbLoaiThietBi_TraCuu.SelectedValue.ToString());
            }
            if (txtChieuDai_TraCuu.Text != string.Empty && txtChieuDay_TraCuu.Text != string.Empty && txtChieuRong_TraCuu.Text != string.Empty)
            {                
                _ThietBiDien.KickThuoc = txtChieuDai_TraCuu.Text.ToString();
                _ThietBiDien.KickThuoc += "x";
                _ThietBiDien.KickThuoc += txtChieuRong_TraCuu.Text.ToString();
                _ThietBiDien.KickThuoc += "x";
                _ThietBiDien.KickThuoc += txtChieuDay_TraCuu.Text.ToString();
            }
            else
            {
                _ThietBiDien.KickThuoc = string.Empty;
            }
            if (txtDonGia_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.DonGia = double.Parse(txtDonGia_TraCuu.Text.ToString());
            }
            if (txtImp_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.Imp = double.Parse(txtImp_TraCuu.Text.ToString());
            }
            if (txtVmp_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.Vmp = double.Parse(txtVmp_TraCuu.Text.ToString());
            }
            if (txtIsc_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.Isc = double.Parse(txtIsc_TraCuu.Text.ToString());
            }
            if (txtVoc_TraCuu.Text != string.Empty)
            {
                _ThietBiDien.Voc = double.Parse(txtVoc_TraCuu.Text.ToString());
            }
            DataTable dt = new DataTable();
            dt = ThietBiDienBUS.TraCuuThietBiDien(_ThietBiDien, _MaThietBi);
            gdvKQ_TraCuu.DataSource = dt;
        }
    }
}